import {use, useState} from "react";


const initialFriends=[
  {
    id:118836,
    name:"Clark",
    image:"https://img95.699pic.com/xsj/09/yc/d8.jpg!/fh/300",
    balance:-5
  },
  {
    id:933372,
    name:"Sarah",
    image:"https://bpic.51yuansu.com/pic3/cover/03/47/97/65e38aaf5904f_260.jpg?x-oss-process=image/resize,w_260/sharpen,100",
    balance:20
  },
  {
    id:499476,
    name:"Anthory",
    image:"https://img95.699pic.com/xsj/0u/hm/d8.jpg!/fh/300",
    balance:0
  }

]

function App() {
    const [friends,setFriends] = useState(initialFriends);
    const [showAddFriend,setShowAddFriend] = useState(false);
    const [selectedFriend,setSelectedFriend] = useState(null);

    function handleShowAddFriend(){
        setShowAddFriend((show)=>!show);
    }

    function handleAddFriend(friend){
        setFriends((friends) =>[...friends,friend]);
        setShowAddFriend(false);
    }

    function handleSelection(friend){
        // setSelectedFriend(friend);
        setSelectedFriend((cur)=> cur?.id === friend.id ? null : friend);
        setShowAddFriend(false);
    }

    function handleSplitBill(value){
        console.log(value);

        setFriends((friends)=>
            friends.map((friend)=>
                friend.id === selectedFriend.id
                    ? {...friend,balance:friend.balance + value }
                    : friend
        )
        );

        setSelectedFriend(null);
    }

  return (
    <div className="app">
      <div className={"sidebar"}>
        <FriendList
            friends={friends}
            selectedFriend = {selectedFriend}
            onSelection ={handleSelection}/>

          {showAddFriend &&  <FormAddFriend onAddFriend={handleAddFriend}/> }

        <Button onClick={handleShowAddFriend}>{showAddFriend ? 'Close' : 'Add Friend'}</Button>
      </div>

        {selectedFriend &&  <FormSplitBill selectedFriend={selectedFriend} onSplitBill = {handleSplitBill} />}
    </div>
  );
}


function FriendList({friends,onSelection,selectedFriend}){

  return (
      <ul>
        {
          friends.map((friend)=>(
              <Friend friend ={ friend } key={friend.id} onSelection={onSelection} selectedFriend={selectedFriend}/>
          ))
        }
      </ul>
  )
}

function Friend({friend,onSelection,selectedFriend}){
    const isSelected = selectedFriend?.id === friend.id;

  return (
      <div>
        <li className={isSelected ? "selected" : ""}>
          <img src={friend.image}  alt={friend.name}/>
          <h3>{friend.name}</h3>

          {
            friend.balance < 0 && (
                  <p className={"red"}>
                    You own {friend.name} ${Math.abs(friend.balance)}
                  </p>
              )
          }
          {
              friend.balance > 0 && (
                  <p className={"green"}>
                    {friend.name} own you  ${Math.abs(friend.balance)}
                  </p>
              )
          }
          {
              friend.balance === 0 && (
                  <p>
                    You and {friend.name} are even
                  </p>
              )
          }

          <Button onClick={()=>onSelection(friend)}>
              {isSelected ? "Close" : "Select"}
          </Button>
        </li>
      </div>

  );
}

function Button({children,onClick}){
  return (
      <button className={"button"} onClick={onClick}>{children}</button>
  );
}

function FormAddFriend({onAddFriend}){
    const [name,setName] = useState('');
    const [image,setImage] = useState("https://img95.699pic.com/xsj/0u/hm/d8.jpg!/fh/300");

    function handleSubmit(e){
        e.preventDefault();
        if(!name || !image)
            return;

        const id = crypto.randomUUID();
        const newFriend = {
            id,
            name,
            image,
            balance:0,
        };

        onAddFriend(newFriend);

        setName('');
        setImage("https://img95.699pic.com/xsj/0u/hm/d8.jpg!/fh/300");
    }

  return (
      <div>
        <form className={"form-add-friend"} onSubmit={handleSubmit}>
          <label htmlFor="">👨Friend Name</label>
          <input type="text" value={name} onChange={(e)=>setName(e.target.value)}/>

          <label htmlFor="">😒Image Url</label>
          <input type="text" value={image} onChange={(e)=>setImage(e.target.value)}/>

          <Button>Add</Button>
        </form>
      </div>
  );

}

function FormSplitBill({selectedFriend,onSplitBill}){
    const [bill,setBill] = useState("");
    const [paidByUser,setPaidByUser] = useState('');
    const paidByFriend = bill ? bill - paidByUser : "";
    const[whoIsPaying,setWhoIsPaying] = useState('user');

    function handleSubmit(e){
        e.preventDefault();

        if(!bill || !paidByUser){
            return;
        }

        onSplitBill(whoIsPaying === 'user' ? paidByFriend : -paidByUser);

    }

  return (
      <form className={"form-split-bill"} onSubmit={handleSubmit}>
        <h2>Split a bill with {selectedFriend.name}</h2>

        <label htmlFor="">👩‍⚖️Bill Value</label>
        <input
            type="text"
            value={bill}
            onChange={(e)=>setBill(Number(e.target.value))}
        />

        <label htmlFor="">‍⚖️Your expense</label>
        <input
            type="text"
            value={paidByUser}
            onChange={(e)=>setPaidByUser(
                Number(e.target.value) > bill ? paidByUser : Number(e.target.value)
            )}
        />

        <label htmlFor="">‍⚖️{selectedFriend.name}'s expense</label>
        <input type="text" disabled value={paidByFriend} />

          <label htmlFor="">‍⚖️ Who is paying the bill</label>
          <select name="" id="" value={whoIsPaying} onChange={(e)=>setWhoIsPaying(e.target.value)}>
              <option value="user">You</option>
              <option value="friend">{selectedFriend.name}</option>
          </select>

        <Button >Split Bill</Button>
      </form>
  );
}

export default App;
